<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="userName">
      <Input v-model="form.userName" placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="code">
      <Row>
        <Col span="15">
          <Input type="password" v-model="form.captcha" placeholder="请输入图片验证码" :maxlength="4">
            <span slot="prepend">
              <Icon type="ios-image" :size="14"/>
            </span>
          </Input>
        </Col>
        <Col span="8" offset="1">
          <img :src="codeSrc" alt="图片验证码" @click="getCodeImg" style="cursor: pointer">
        </Col>
      </Row>
    </FormItem>
    <FormItem style="margin-bottom: 12px;">
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>

<script>
import URL from '@/api/login'
export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    },
    captchaRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '图片验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  data () {
    return {
      form: {
        userName: 'super_admin',
        password: '',
        captcha: ''
      },
      codeSrc: ''
    }
  },
  computed: {
    rules () {
      return {
        userName: this.userNameRules,
        password: this.passwordRules,
        captcha: this.captchaRules
      }
    }
  },
  mounted () {
    this.getCodeImg()
  },
  methods: {
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$emit('on-success-valid', {
            userName: this.form.userName,
            password: this.form.password,
            captcha: this.form.captcha
          })
        }
      })
    },
    getCodeImg () {
      this.form.captcha = ''
      this.codeSrc = `${URL.captcha}?t=${Math.random() * 1000}`
    }
  }
}
</script>
